﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Collections;
using System.Drawing;
using System.Configuration;

public partial class legaldocs : System.Web.UI.Page
{
    SqlConnection CNx = new SqlConnection();
    SqlConnection CNx2 = new SqlConnection();
    Utilitarios Util = new Utilitarios();
    string IDU;

    protected void Page_Load(object sender, EventArgs e)
    {
        CNx.ConnectionString = Utilitarios.Conexion2;
        CNx2.ConnectionString = Utilitarios.Conexion;
        if (Session["IDUsuario"] == null)
        {
           Response.Redirect("Default.aspx");
        };
        IDU = Session["IDUsuario"].ToString();
        if (!IsPostBack)
        {
            cargardatos();
            datosmateria();
            Filtrar();
        }
        if (Page.Request.Params["__EVENTTARGET"] == "GrabarExp") GrabarExp();
        if (Page.Request.Params["__EVENTTARGET"] == "ExportarXLS") exportarXLS();
    }

    private void cargardatos()
    {
        CNx.Open();
        string msg = "Select * from LEG_TipoProceso";
        SqlCommand tb = new SqlCommand(msg, CNx);
        SqlDataReader Dr = tb.ExecuteReader();
        ArrayList L1 = new ArrayList();

        while (Dr.Read())
        {
            L1.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
        }
        Dr.Close();
        cmbNtp.DataSource = L1;
        cmbNtp.DataTextField = "Nombre";
        cmbNtp.DataValueField = "Tag";
        cmbNtp.DataBind();
        //Dr.Close();

        msg = "Select * from LEG_VMateria";
        ArrayList L2 = new ArrayList();
        ArrayList L5 = new ArrayList();
        tb = new SqlCommand(msg, CNx);
        Dr = tb.ExecuteReader();
        L5.Add(new listas("0","S/D"));
        while (Dr.Read())
        {
            L2.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
            L5.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
        }
        Dr.Close();
        cmbNmat.DataSource = L2;
        cmbNmat.DataTextField = "Nombre";
        cmbNmat.DataValueField = "Tag";
        cmbNmat.DataBind();
        
        cmbMMateria.DataSource=L5;
        cmbMMateria.DataTextField="Nombre";
        cmbMMateria.DataValueField="Tag";
        cmbMMateria.DataBind();

        //Dr.Close();

        //msg = "Select * from LEG_Ubicacion";
        //ArrayList L6 = new ArrayList();
        //tb = new SqlCommand(msg, CNx);
        //Dr = tb.ExecuteReader();
        //while (Dr.Read())
        //{
        //    L6.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
        //}
        //Dr.Close();
        //cmbUbiFis.DataSource = L6;
        //cmbUbiFis.DataTextField = "Nombre";
        //cmbUbiFis.DataValueField = "Tag";
        //cmbUbiFis.DataBind();
        //Dr.Close();


        CNx.Close();
        CNx2.Open();
        msg = "Select * from SIS_VUAPP where APP_ID=7 and SEG_1 >=256";
        ArrayList L3 = new ArrayList();
        tb = new SqlCommand(msg, CNx2);
        Dr = tb.ExecuteReader();
        while (Dr.Read())
        {
            L3.Add(new listas(Dr[0].ToString(), Dr[2].ToString()));
        }
        Dr.Close();
        cmbNabogado.DataSource = L3;
        cmbNabogado.DataTextField = "Nombre";
        cmbNabogado.DataValueField = "Tag";
        cmbNabogado.DataBind();
        //Dr.Close();
        CNx2.Close();
        DateTime Hoy = DateTime.Today;
        DateTime Hmes = Hoy.AddMonths(-1);
        txtFfin.Text =  Hoy.ToString("dd/MM/yyyy");
        txtFinicio.Text = Hmes.ToString("dd/MM/yyyy");
        
    }

    private void datosmateria()
    {
        string IDM = cmbNmat.SelectedValue;
        CNx.Open();
        string msg = "Select * from LEG_SMateria where IDM="+IDM;
        SqlCommand tb = new SqlCommand(msg, CNx);
        SqlDataReader Dr = tb.ExecuteReader();
        ArrayList L1 = new ArrayList();
        while (Dr.Read())
        {
            L1.Add(new listas(Dr[0].ToString(), Dr[2].ToString()));
        }
        Dr.Close();
        cmbNmot.DataSource = L1;
        cmbNmot.DataTextField = "Nombre";
        cmbNmot.DataValueField = "Tag";
        cmbNmot.DataBind();
        Dr.Close();
        msg = "Select NSala from LEG_VMateria where IDM=" + IDM;
        tb = new SqlCommand(msg, CNx);
        lblNlocal.Text = tb.ExecuteScalar().ToString();
        msg = "Select * from LEG_Sala where IDM=" + IDM;
        tb = new SqlCommand(msg, CNx);
        Dr = tb.ExecuteReader();
        ArrayList L2 = new ArrayList();
        while (Dr.Read())
        {
            L2.Add(new listas(Dr[0].ToString(), Dr[2].ToString()));
        }
        Dr.Close();
        cmbNlocal.DataSource = L2;
        cmbNlocal.DataTextField = "Nombre";
        cmbNlocal.DataValueField = "Tag";
        cmbNlocal.DataBind();
        Dr.Close();
        CNx.Close();
    }

    protected void cmbNmat_SelectedIndexChanged(object sender, EventArgs e)
    {
        datosmateria();
    }
    protected void btnFiltra_Click(object sender, EventArgs e)
    {
        //GrabarExp();
        Filtrar();
    }
        //msg = "Select * from LEG_Expedientes";

    private void GrabarExp()
       {
           string msg = "";
           if (hidFlag.Value == "1")
           {
               string Vence = "0", EDem = "0";
               if (chkVfecha.Checked == true) Vence = "1";
               if (rbtDado.Checked == true) EDem = "1";

               msg = "LEG_NExpe " + IDU + ",'" + txtNexp.Text + "'," + cmbNtp.SelectedValue + "," + cmbNmat.SelectedValue + "," + cmbNmot.SelectedValue + "," + cmbNlocal.SelectedValue;
               msg = msg + ",@FechaEx," + Vence + ",@FechaV," + EDem + ",'" + txtNdemanda.Text + "','" + txtNsumilla.Text + "','" + txtNjuez.Text + "'," + cmbNabogado.SelectedValue + ",";
               msg = msg + txtNsoles.Text + "," + txtNus.Text;

               string ftt = txtVfecha.Text;

               if (ftt == "") ftt = txtNfecha.Text;

               ftt = Util.Afecha(ftt);
               DateTime F1 = DateTime.Parse(ftt);

               ftt = txtNfecha.Text;
               ftt = Util.Afecha(ftt);
               DateTime F2 = DateTime.Parse(ftt);

               CNx.Open();
               SqlCommand tb = new SqlCommand(msg, CNx);
               tb.Parameters.Add("@FechaV", SqlDbType.DateTime).Value = F1;
               tb.Parameters.Add("@FechaEx", SqlDbType.DateTime).Value = F2;
               int idActu = (int)tb.ExecuteScalar();

               //tb.ExecuteNonQuery();
               CNx.Close();
               //string gg = FUExpediente.FileName.ToString();
               string archi = "Documentos/Actuados/A" + Util.Ceros(idActu, 6) + ".pdf";
               FUExpediente.SaveAs(MapPath("~/" + archi));
               Filtrar();
       }
    }

    private void Filtrar()
    {
        string filtro = "", union = " where ",EDem="";
        if (txtExpediente.Text != "")
        {
            filtro = union + " (NroExped like '" + txtExpediente.Text+"') ";
            union = " and ";
        }

        if (txtDemandados.Text != "")
        {
            if (rdb1.Checked) EDem = "1"; else EDem = "0";
            filtro = filtro + union + " EstDem =" + EDem + " and (PDemanda like '" + txtDemandados.Text+"') ";
            union = " and ";
        }

        if (cmbMMateria.SelectedValue != "0")
        {
            filtro = filtro + union + " idMat =" + cmbMMateria.SelectedValue;
            union = " and ";
        }
        DateTime FF1=DateTime.Today, FF2=FF1;
        string Acce = cmbAccesos.SelectedValue;
        if (Acce != "0")
        {
            switch (Acce)
            {
                case "1":  //Ingresos de la ultima semana
                    FF2 = DateTime.Today;
                    FF2 =  new DateTime(FF2.Year, FF2.Month, FF2.Day, 23, 59, 59);
                    FF1 = FF2.AddDays(-7);
                    FF1 = new DateTime(FF1.Year, FF1.Month, FF1.Day, 0, 0, 0);
                    filtro = filtro + union + " (FechaExped between @f1 AND @f2) ";
                    union = " and ";
                    break;
                case "2": //Vencimientos proximos 7 días
                    FF1 = DateTime.Today;
                    FF1 =  new DateTime(FF1.Year, FF1.Month, FF1.Day, 0, 0, 0);
                    FF2 = FF1.AddDays(7);
                    FF2 = new DateTime(FF2.Year, FF2.Month, FF2.Day, 23, 59, 59);

                    filtro = filtro + union + "(IDEx in (select IDExp from leg_actuados where EstVcmto=true and FechaVcmto between @f1 AND @f2))";
                    union = " and ";
                    break;
                case "3":  //Vencimientos proximos 3 días
                    FF1 = DateTime.Today;
                    FF1 =  new DateTime(FF1.Year, FF1.Month, FF1.Day, 0, 0, 0);
                    FF2 = FF1.AddDays(3);
                    FF2 = new DateTime(FF2.Year, FF2.Month, FF2.Day, 23, 59, 59);

                    filtro = filtro + union + "(IDEx in (select IDExp from leg_actuados where EstVcmto=true and FechaVcmto between @f1 AND @f2))";
                    union = " and ";
                    break;
                case "4": //Vencidos
                    FF1 = DateTime.Today;
                    FF1 =  new DateTime(FF1.Year, FF1.Month, FF1.Day, 23, 59, 59);
                    filtro = filtro + union + "(IDEx in (select IDExp from leg_actuados where EstVcmto=true and FechaVcmto < @f1))";
                    break;
                case "5":  //Actuados los ultimos 7 dias
                    FF2 = DateTime.Today;
                    FF2 =  new DateTime(FF2.Year, FF2.Month, FF2.Day, 23, 59, 59);
                    FF1 = FF2.AddDays(-7);
                    FF1 = new DateTime(FF1.Year, FF1.Month, FF1.Day, 0, 0, 0);
                    filtro = filtro + union + " (IDEx in (select IDExp from leg_actuados where Fecha between @f1 AND @f2)) ";
                    union = " and ";
                    break;
                default:
                    Console.WriteLine("Default case");
                    break;
                case "6":  //Vencen hoy
                    FF1 = DateTime.Today;
                    //FF1 =  new DateTime(FF1.Year, FF1.Month, FF1.Day, 23, 59, 59);
                    filtro = filtro + union + "(IDEx in (select IDExp from leg_actuados where FechaVcmto = @f1))";
                    break;
            }

        }
        else
        {
            string ftt = txtFfin.Text;
            ftt = Util.Afecha(ftt) + " 23:59:59";
            FF2 = DateTime.Parse(ftt);

            ftt = txtFinicio.Text;
            ftt = Util.Afecha(ftt) + " 00:00:00";
            FF1 = DateTime.Parse(ftt);

            if (rdb3.Checked)
            {
                filtro = filtro + union + " (FechaExped between @f1 AND @f2) ";
                union = " and ";
            }
            else
            {
                filtro = filtro + union + "(IDEx in (select IDExp from leg_actuados where fecha between @f1 AND @f2))";
                union = " and ";
            }
        }

        try
        {
            CNx.Open();
            string msg = "Select * from LEG_VExped " + filtro;
            DataTable dt = new DataTable();
            SqlDataAdapter Da = new SqlDataAdapter(msg, CNx);
            Da.SelectCommand.Parameters.AddWithValue("@f1", FF1);
            Da.SelectCommand.Parameters.AddWithValue("@f2", FF2);
            Da.Fill(dt);
            gvListado.DataSource = dt;
            gvListado.DataBind();
        }
        catch (Exception ex)
        {
            string err = ex.ToString();
        }
        finally
        {
            CNx.Close();
        }

    
       
    }

    protected void gvListado_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       if (e.CommandName == "EditarExp")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            string idcon = gvListado.DataKeys[index].Value.ToString();
            EditarExped(idcon);
        }
    }

    private void EditarExped(string ID)
    {
        Session["IDUsuario"] = IDU;
        Session["IDExpediente"] = ID;
        Response.Redirect("DetExp.aspx");
    }

    protected void gvListado_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvListado.PageIndex = e.NewPageIndex;
        Filtrar();
    }

    private void exportarXLS()
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            //To Export all pages
            gvListado.AllowPaging = false;
            Filtrar();
            //this.BindGrid();
            gvListado.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in gvListado.HeaderRow.Cells)
            {
                cell.BackColor = gvListado.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in gvListado.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = gvListado.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = gvListado.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";
                }
            }
            gvListado.RenderControl(hw);
            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }

}